package com.jmb.waimao.config;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * GreenMail configuration for local mail server testing
 */
@Configuration
public class GreenMailConfig {

    @Value("${greenmail.smtp.host:localhost}")
    private String smtpHost;

    @Value("${greenmail.smtp.port:3025}")
    private int smtpPort;

    @Value("${greenmail.imap.port:3143}")
    private int imapPort;

    @Value("${greenmail.pop3.port:3110}")
    private int pop3Port;

    @Value("${greenmail.user:user}")
    private String user;

    @Value("${greenmail.password:password}")
    private String password;

    @Value("${greenmail.email:user@localhost}")
    private String email;

    private GreenMail greenMail;

    /**
     * Configure GreenMail server
     *
     * @return GreenMail
     */
    @Bean
    public GreenMail greenMail() {
        // Configure SMTP, IMAP, and POP3 servers
        ServerSetup[] serverSetups = {
            new ServerSetup(smtpPort, smtpHost, ServerSetup.PROTOCOL_SMTP),
            new ServerSetup(imapPort, smtpHost, ServerSetup.PROTOCOL_IMAP),
            new ServerSetup(pop3Port, smtpHost, ServerSetup.PROTOCOL_POP3)
        };

        greenMail = new GreenMail(serverSetups);

        // Create user account
        greenMail.setUser(email, user, password);

        // Start the server
        greenMail.start();

        return greenMail;
    }

    @PreDestroy
    public void stopGreenMail() {
        if (greenMail != null) {
            greenMail.stop();
        }
    }
}
